package com.phrp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.phrp.entity.User;
import com.phrp.exception.CustomizationException;
import com.phrp.util.returnResult.ResponseResult;
import com.phrp.util.returnResult.ReturnInfoEnum;
import com.phrp.dao.UserDao;
import com.phrp.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.phrp.util.tengXunSms.TengXunSmsUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ssc
 * @since 2024-05-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TengXunSmsUtils smsUtil;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @Override
    public ResponseResult getCode(String phone) {
        String s = smsUtil.sendSms(phone);
        if("false".equals(s)){
            throw new CustomizationException(ReturnInfoEnum.GET_CODE_ERROR);
        }
        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 注册
     * @param map
     * @return
     */
    @Override
    public ResponseResult register(HashMap<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code"); // 获取验证码

        // 验证短信验证码
        if(!code.equals(redisTemplate.opsForValue().get(phone))){
            return ResponseResult.error("2002","验证码错误");
        }

        // 查询数据库
        int i = userDao.selectByPhone(phone);
        if(i !=0 ){
            return ResponseResult.error("2001","用户已存在");
        }

        Md5Hash md5Hash = new Md5Hash(map.get("password"), phone, 1024);

        // 密码加密
        String password = md5Hash.toHex();

        User user = new User();
        user.setUUuid(UUID.randomUUID().toString().replace("-",""));
        user.setPassword(password);
        user.setPhone(phone);
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());

        int insert = userDao.insert(user);
        if(insert != 1){
            throw new CustomizationException(ReturnInfoEnum.DATA_FAIL);
        }

        return new ResponseResult(ReturnInfoEnum.SUCCESS);
    }

    /**
     * 通过手机号获取用户信息
     * @param phone
     * @return
     */
    @Override
    public User getByPhone(String phone) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("phone",phone);
        User user = userDao.selectOne(query);
        return user;
    }
}
